package com.crcode.crm.service.retrieval.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrRequest.METHOD;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.crcode.crm.bean.user.UserBean;
import com.crcode.crm.service.retrieval.RetrievalService;
import com.crcode.crm.service.role.RoleUserService;
import com.crcode.crm.utils.DateUtil;
import com.crcode.crm.utils.PageVo;
import com.crcode.crm.utils.PropertiesUtil;
import com.crcode.crm.utils.ResultPageUtil;

/**
 * 检索业务处理层
 * 
 * @author lxw
 * @date 2018年6月7日 下午2:36:52
 * @version V1.0
 */
@Service(value = "retrievalService")
@Transactional
public class RetrievalServiceImpl implements RetrievalService {
	
	@Autowired
	private RoleUserService roleUserService;
	
	/**
	 * 公共查询
	 * @author lxw
	 * @date 2019年3月25日
	 * @param table
	 *            企业表：data_enterprise；项目表：data_project
	 * @param text
	 *            模糊匹配的值，多个以@#@符号隔开，例如：张三@#@李四@#@王五
	 * @param higthText
	 *            高级查询的条件json字符串，多个条件以@#@隔开；条件中为或与非逻辑(AND/OR/非得时候 为:AND,-field,值,0)、字段、值、精确或者模糊(1、模糊，0、精确)；例如：AND,name,张三,1@#@AND,-jop,人寿,0
	 * @param vo 
	 *            分页参数 pageIndex,pageSize必传，orderBy 排序字段，只能单个,orderDesc 正序0，反序1
	 * @param user
	 *            用户
	 * @return
	 */
	public ResultPageUtil comSearch(String table, String text, String higthText, PageVo vo, UserBean user) {
		ResultPageUtil rp = new ResultPageUtil();
		try {
			int startIndex = 0;
			if (vo.getPageIndex() <= 1) {
				startIndex = 0;
				vo.setPageIndex(1);
			} else {
				startIndex = (vo.getPageIndex() - 1) * vo.getPageSize();
			}

			String query = "tableName:" + table + " ";
			
			//判断权限
			if(!user.getLoginName().toLowerCase().equals("admin") && (this.roleUserService.findByRoleUuidAndUserUuid("admin", user.getUuid()).size()<=0)){
				query +=  "AND (liable_user_uuid:"+user.getUuid()+" OR search_power_user_uuids:*"+user.getUuid()+"*) ";
			}
			// 定义查询字段
			String fields = "";
			if (table.equals("data_enterprise")) {
				fields = "ent_name,ent_address,ent_one_person,ent_two_person,ent_industry_one,ent_industry_two,ent_upstream,ent_downstream,"
						+ "ent_stock_right,ent_product,ent_mode,ent_needs_urgent,ent_needs_commonly";

			} else {// 图集匹配字段
				fields = "pro_name,ent_name,pro_remarks";
			}

			// 拼接模糊查询字段
			if (text.length() > 0) {
				String queryTerm = "";
				String[] fieldL = fields.split(",");
				for (String cs : text.split("@#@")) {
					for (int i = 0; i < fieldL.length; i++) {
						if (i == 0) {
							queryTerm = fieldL[i] + ":*" + cs + "* ";
						} else {
							queryTerm += " OR " + fieldL[i] + ":*" + cs + "* ";
						}
					}
					query += "AND(" + queryTerm + ") ";
				}
			}
			// 高级查询拼接
			if (higthText.trim().length() > 0) {
				String[] conditions = higthText.split("@#@");
				for (String str : conditions) {
					String[] term = str.split(",");
					String field = term[1].trim();

					if (field.equals("create_time") || field.equals("last_edit_time")
							|| field.equals("next_step_time")) {
						if (term[2].trim().length() > 0) {
							query += term[0].toUpperCase() + " " + field + ":[" + term[2] + "]";
						}
					} else if ("data_enterprise".equals(table) && "ent_one_person".equals(field)) { // 如果是查询企业的联系人，拼接两个联系人的查询
						if (term[3].trim().equals("1")) {
							query += term[0].toUpperCase() + " (ent_one_person:*"+term[2]+"* OR ent_two_person:*"+term[2]+"*) ";
						} else {
							query += term[0].toUpperCase() + " (ent_one_person:"+term[2]+" OR ent_two_person:"+term[2]+") ";
						}
					} else if ("data_enterprise".equals(table) && "ent_needs_urgent".equals(field)) { // 如果是查询企业的需求，拼接两个需求的查询
						if (term[3].trim().equals("1")) {
							query += term[0].toUpperCase() + " (ent_needs_urgent:*"+term[2]+"* OR ent_needs_commonly:*"+term[2]+"*) ";
						} else {
							query += term[0].toUpperCase() + " (ent_needs_urgent:"+term[2]+" OR ent_needs_commonly:"+term[2]+") ";
						}
					} else {
						if (term[2].trim().length() > 0) {
							// 1、like,0、等于
							if (term[3].trim().equals("1")) {
								query += term[0].toUpperCase() + " " + term[1] + ":*" + term[2] + "* ";
							} else {
								query += term[0].toUpperCase() + " " + term[1] + ":" + term[2] + " ";
							}
						}
					}
				}
			}

			System.out.println(query);

			PropertiesUtil p = new PropertiesUtil();
			// 获取properties配置文件数据
			String solrurl = p.getTerm("solr.properties", "solrcore");
			HttpSolrServer solr = new HttpSolrServer(solrurl);
			// solr查询
			SolrQuery params = new SolrQuery(query);
			params.setStart(startIndex);
			params.setRows(vo.getPageSize());
			if (vo.getOrderBy() != null && vo.getOrderBy().length() > 0) {
				if (vo.getOrderDesc()==1) {
					params.addSort(vo.getOrderBy(), ORDER.desc);
				} else {
					params.addSort(vo.getOrderBy(), ORDER.asc);
				}
			}
			// 返回指定的字段值
			/*
			 * params.addField("id"); params.addField("tableName");
			 */
			QueryResponse response = solr.query(params, METHOD.POST);
			SolrDocumentList list = response.getResults();
			
			rp.setCurrentPage(vo.getPageIndex());
			rp.setPageSize(vo.getPageSize());
			rp.setTotal(list.getNumFound());
			Integer tatalPages = 1;
			if (list.getNumFound() % vo.getPageSize() == 0) {
				tatalPages = (int) (list.getNumFound() / vo.getPageSize());
			} else {
				tatalPages = (int) (list.getNumFound() / vo.getPageSize() + 1);
			}
			rp.setTotalPages(tatalPages);
			rp.setRows(list);
			return rp;
		} catch (Exception e) {
			e.printStackTrace();
			return rp;
		}
	}
	public static void main(String[] args) {
		RetrievalServiceImpl r = new RetrievalServiceImpl();

		UserBean user = new UserBean();
		PageVo vo = new PageVo();
		vo.setPageIndex(1);
		vo.setPageSize(10);
		user.setLoginName("admin");
		user.setUuid("1");
		Object obj = "";
//		obj = r.comSearch("data_enterprise", "", "AND,ent_name,结构,1@#@OR,ent_name,,1", vo, user);
//		obj = r.searchProgressAndAccesssory("data_accessory", "", "", vo);
//		obj = r.messageDetails(2, vo, user);
//		obj = r.messageCount(user);
//		System.out.println(JSON.toJSONString(obj));
//		obj = r.messageDetails(0, vo, user);
//		System.out.println(JSON.toJSONString(obj));
//		obj = r.messageDetails(1, vo, user);
//		System.out.println(JSON.toJSONString(obj));
//		obj = r.messageDetails(2, vo, user);
//		System.out.println(JSON.toJSONString(obj));
		obj = r.loadProgressGroupData("0dcd553ca9f542c2a16beb51bcc9cee7");
		System.out.println(JSON.toJSONString(obj));

	}
	/**
	 * 附件方案进度检索
	 * @author lxw
	 * @date 2019年4月15日
	 * @param table，方案：data_accessory ；进度：data_progress
	 * @param text 检索词 123@#@12341@#@12312
	 * @param higthText
	 *        高级查询的条件json字符串，多个条件以@#@隔开；条件中为或与非逻辑(AND/OR/非得时候 为:AND,-field,值,0)、字段、值、精确或者模糊(1、模糊，0、精确)；例如：AND,name,张三,1@#@AND,-jop,人寿,0
	 * @param vo 分页工具类 
	 * @return
	 */
	public ResultPageUtil searchProgressAndAccesssory(String table, String text,String higthText,PageVo vo) {
		ResultPageUtil rp = new ResultPageUtil();
		try {
			
			String query = "tableName:" + table + " ";
			
			// 定义查询字段
			String fields = "";
			if (table.equals("data_accessory")) {
				fields = "acc_title,plan_describe";

			} else {// 图集匹配字段
				fields = "pro_title,pro_describe";
			}

			// 拼接模糊查询字段
			if (text.length() > 0) {
				String queryTerm = "";
				String[] fieldL = fields.split(",");
				for (String cs : text.split("@#@")) {
					for (int i = 0; i < fieldL.length; i++) {
						if (i == 0) {
							queryTerm = fieldL[i] + ":*" + cs + "* ";
						} else {
							queryTerm += " OR " + fieldL[i] + ":*" + cs + "* ";
						}
					}
					query += "AND(" + queryTerm + ") ";
				}
			}
			// 高级查询拼接
			if (higthText.trim().length() > 0) {
				String[] conditions = higthText.split("@#@");
				for (String str : conditions) {
					String[] term = str.split(",");
					String field = term[1].trim();
					//判断要查询的值是否为空，为空则跳出本次循环
					if (term[2].trim().length() > 0) {
						continue;
					}
					if (field.equals("create_time") || field.equals("next_step_time")) {
						query += term[0].toUpperCase() + " " + field + ":[" + term[2] + "]";
					} else {
						// 1、like,0、等于
						if (term[3].trim().equals("1")) {
							query += term[0].toUpperCase() + " " + term[1] + ":*" + term[2] + "* ";
						} else {
							query += term[0].toUpperCase() + " " + term[1] + ":" + term[2] + " ";
						}
					}
				}
			}

			System.out.println(query);

			PropertiesUtil p = new PropertiesUtil();
			// 获取properties配置文件数据
			String solrurl = p.getTerm("solr.properties", "solrcore");
			HttpSolrServer solr = new HttpSolrServer(solrurl);
			// solr查询
			SolrQuery params = new SolrQuery(query);
			
			//设置分页
			int startIndex = 0;
			if (vo.getPageIndex() <= 1) {
				startIndex = 0; 
				vo.setPageIndex(1);
			} else {
				startIndex = (vo.getPageIndex() - 1) * vo.getPageSize();
			}
			params.setStart(startIndex);
			params.setRows(vo.getPageSize());
			//设置排序
			if (vo.getOrderBy() != null && vo.getOrderBy().length() > 0) {
				if (vo.getOrderDesc()==1) {
					params.addSort(vo.getOrderBy(), ORDER.desc);
				} else {
					params.addSort(vo.getOrderBy(), ORDER.asc);
				}
			}
			// 返回指定的字段值
			/*
			 * params.addField("id"); params.addField("tableName");
			 */
			QueryResponse response = solr.query(params, METHOD.POST);
			SolrDocumentList list = response.getResults();
			
			rp.setCurrentPage(vo.getPageIndex());
			rp.setPageSize(vo.getPageSize());
			rp.setTotal(list.getNumFound());
			Integer tatalPages = 1;
			if (list.getNumFound() % vo.getPageSize() == 0) {
				tatalPages = (int) (list.getNumFound() / vo.getPageSize());
			} else {
				tatalPages = (int) (list.getNumFound() / vo.getPageSize() + 1);
			}
			rp.setTotalPages(tatalPages);
			rp.setRows(list);
			return rp;
		} catch (Exception e) {
			e.printStackTrace();
			return rp;
		}
	}
	/**
	 * 查询提示总数
	 * @author lxw
	 * @date 2019年4月15日
	 * @param user
	 * @return
	 */
	public Map<String, Object> messageCount(UserBean user){
		Map<String, Object> map = new HashMap<>();
		PageVo vo = new PageVo();
		vo.setPageIndex(1);
		vo.setPageSize(10);
		map.put("enterprise", this.messageDetails(0, vo, user).getTotal());
		map.put("project", this.messageDetails(1, vo, user).getTotal());
		map.put("progress", this.messageDetails(2, vo, user).getTotal());
		return map;
	}
	/**
	 * 提示详情
	 * @author lxw
	 * @date 2019年4月15日
	 * @param type 0、企业联系人生日，1、项目下一步时间，2、进度下一步时间，3、首页查询企业进度，4、首页查询项目进度
	 * @param vo 分页参数
	 * @param user 
	 * @return
	 */
	public ResultPageUtil messageDetails(Integer type,PageVo vo,UserBean user){
		ResultPageUtil rp = new ResultPageUtil();
		try {
			Date nowTime = new Date();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(nowTime);
			calendar.add(Calendar.DATE, -1);//当前日期前一天
			Date date1= calendar.getTime();
			String sj1 = DateUtil.DateToStr(date1, "yyyy-MM-dd")+"T23:59:59.999Z";
			calendar = Calendar.getInstance();
			calendar.setTime(nowTime);
			calendar.add(Calendar.DATE, 1);//当前日期后一天
			date1= calendar.getTime();
			String sj2 = DateUtil.DateToStr(date1, "yyyy-MM-dd")+"T23:59:59.999Z";
			System.out.println(sj1+" TO "+sj2);
			
			String query = "";
			
			//拼接用户权限
			String userPower1 = "";
			String userPower2 = "";
			if(!user.getLoginName().toLowerCase().equals("admin") && (this.roleUserService.findByRoleUuidAndUserUuid("admin", user.getUuid()).size()<=0)){
				userPower1 += " AND ( liable_user_uuid:"+user.getUuid()+" OR search_power_user_uuids:*"+user.getUuid()+"* )";//查询当前登录者是否在权限列表中
				userPower2 += " AND ( create_user_uuid:"+user.getUuid()+" OR search_power_user_uuids:*"+user.getUuid()+"* )";//查询当前登录者是否在权限列表中
			}
			//1、查询生日提醒
			if(type==0){
				query = "tableName:data_enterprise";
				query += userPower1;
				query += " AND ( ent_one_birthday :["+sj1+" TO "+sj2+ "] OR ent_two_birthday:["+sj1+" TO "+sj2+ "] )";//
				System.out.println("生日："+query);
			}
			
			//2、查询项目下一步进度
			if(type==1){
				query = "tableName:data_project";
				query += userPower1;
				query += " AND pro_stats :0 AND read_stats:0";//状态正常、且未读
				query += " AND next_step_time :[* TO "+sj2+ "]";//在当前时间后一天之前的所有
				System.out.println("项目下一步时间："+query);
			}
		
			//3、查询进度消息
			if(type==2){
				query = "tableName:data_progress";
				query += userPower2;
				query += " AND pro_stats :0 AND read_stats:0";//状态正常、且未读
				query += " AND next_step_time :[* TO "+sj2+ "]";//在当前时间后一天之前的所有
				System.out.println("维护进度下一步时间："+query);
			}
			
			//4、首页查询企业进度
			if(type==3){
				query = "tableName:data_progress";
				query += userPower2;
				query += " AND pro_type:1 AND pro_stats :0 AND read_stats:0";//类型为企业、状态正常、且未读
			}
			//5、首页查询项目进度
			if(type==4){
				query = "tableName:data_progress";
				query += userPower2;
				query += " AND pro_type:2 AND pro_stats :0 AND read_stats:0";//类型为项目、状态正常、且未读
			}
			
			PropertiesUtil p = new PropertiesUtil();
			// 获取properties配置文件数据
			String solrurl = p.getTerm("solr.properties", "solrcore");
			HttpSolrServer solr = new HttpSolrServer(solrurl);
			// solr查询
			SolrQuery params = new SolrQuery(query);
			
			//设置分页
			int startIndex = 0;
			if (vo.getPageIndex() <= 1) {
				startIndex = 0; 
				vo.setPageIndex(1);
			} else {
				startIndex = (vo.getPageIndex() - 1) * vo.getPageSize();
			}
			params.setStart(startIndex);
			params.setRows(vo.getPageSize());
			
			//设置排序
			if (vo.getOrderBy() != null && vo.getOrderBy().length() > 0) {
				if (vo.getOrderDesc()==1) {
					params.addSort(vo.getOrderBy(), ORDER.desc);
				} else {
					params.addSort(vo.getOrderBy(), ORDER.asc);
				}
			}
			
			QueryResponse response = solr.query(params, METHOD.POST);
			SolrDocumentList list = response.getResults();
			
			rp.setTotal(list.getNumFound());
			Integer tatalPages = 1;
			if (list.getNumFound() % vo.getPageSize() == 0) {
				tatalPages = (int) (list.getNumFound() / vo.getPageSize());
			} else {
				tatalPages = (int) (list.getNumFound() / vo.getPageSize() + 1);
			}
			rp.setCurrentPage(vo.getPageIndex());
			rp.setPageSize(vo.getPageSize());
			rp.setTotalPages(tatalPages);
			rp.setRows(list);
			return rp;
		} catch (Exception e) {
			e.printStackTrace();
			return rp;
		}
	}
	
	public List<Object> loadProgressGroupData(String uuid){
		try{
			String query = "tableName:data_progress";
			query += " AND data_uuid:"+uuid;
			query += " AND puuid :0";
			PropertiesUtil p = new PropertiesUtil();
			// 获取properties配置文件数据
			String solrurl = p.getTerm("solr.properties", "solrcore");
			HttpSolrServer solr = new HttpSolrServer(solrurl);
			// solr查询
			SolrQuery params = new SolrQuery(query);
			params.addSort("create_time", ORDER.asc);
			QueryResponse response = solr.query(params, METHOD.POST);
			SolrDocumentList list = response.getResults();
			List<Object> l = new ArrayList<>();
			for (SolrDocument s : list) {
				l.add(s);
				query = "tableName:data_progress";
				query += " AND data_uuid:"+uuid;
				query += " AND puuid :"+s.get("uuid");
				params = new SolrQuery(query);
				params.addSort("create_time", ORDER.asc);
				response = solr.query(params, METHOD.POST);
				l.addAll(response.getResults());
			}
			return l;
		
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
